import { GAME_CONFIG } from './game-config.js';
import { GameState } from './game-state.js';
import { Player } from './player.js';
import { ParticleSystem } from './particle-system.js';

/**
 * 游戏引擎主类
 * @description 整合所有游戏组件，管理游戏主循环
 */
export class GameEngine {
    constructor(canvas) {
        this.canvas = canvas;
        this.ctx = canvas.getContext('2d');

        // 初始化游戏组件
        this.gameState = new GameState();
        this.player = new Player(canvas);
        this.particleSystem = new ParticleSystem();

        // 游戏对象数组
        this.obstacles = [];
        this.powerUps = [];

        // 输入控制
        this.keys = {};

        // 绑定事件
        this.bindEvents();

        // 初始化游戏
        this.init();
    }

    /**
     * 初始化游戏
     */
    init() {
        this.initRoad();
        this.updateUI();
        this.gameLoop();
    }

    /**
     * 绑定事件监听
     */
    bindEvents() {
        document.addEventListener('keydown', (e) => {
            this.keys[e.code] = true;

            if (e.code === 'Space') {
                e.preventDefault();
                this.gameState.togglePause();
            }
        });

        document.addEventListener('keyup', (e) => {
            this.keys[e.code] = false;
        });
    }

    /**
     * 初始化赛道
     */
    initRoad() {
        this.roadSegments = [];
        for (let i = 0; i < GAME_CONFIG.ROAD.TOTAL_SEGMENTS; i++) {
            this.roadSegments.push({
                index: i,
                curve: Math.sin(i * 0.1) * 0.5,
                elevation: Math.sin(i * 0.05) * 100,
                color: i % 2 === 0 ? GAME_CONFIG.COLORS.ROAD : GAME_CONFIG.COLORS.BACKGROUND
            });
        }
    }

    /**
     * 更新游戏状态
     */
    update() {
        if (this.gameState.paused || !this.gameState.gameRunning) {
            return;
        }

        this.updateSpeed();
        this.updatePlayer();
        this.updateObjects();
        this.updateParticles();
        this.checkCollisions();
        this.updateGameState();
    }

    /**
     * 更新速度
     */
    updateSpeed() {
        if (this.keys.ArrowUp && this.gameState.speed < this.player.maxSpeed) {
            this.gameState.speed += this.player.acceleration;
        } else if (this.keys.ArrowDown && this.gameState.speed > 0) {
            this.gameState.speed -= this.player.deceleration;
        } else if (this.gameState.speed > 0) {
            this.gameState.speed -= this.player.deceleration * this.player.friction;
        }

        this.gameState.speed = Math.max(0, Math.min(this.gameState.speed, this.player.maxSpeed));
    }

    /**
     * 更新玩家
     */
    updatePlayer() {
        this.player.update(this.keys, this.gameState.speed);

        // 添加尾气效果
        if (this.gameState.speed > 50) {
            this.particleSystem.createExhaust(
                this.player.x,
                this.player.y + this.player.height / 2,
                GAME_CONFIG.COLORS.PARTICLE_DEFAULT
            );
        }
    }

    /**
     * 更新游戏对象
     */
    updateObjects() {
        // 更新障碍物
        this.obstacles.forEach(obstacle => {
            obstacle.y += this.gameState.speed * 0.1;
        });

        // 更新道具
        this.powerUps.forEach(powerUp => {
            powerUp.y += this.gameState.speed * 0.1;
        });

        // 移除超出屏幕的对象
        this.obstacles = this.obstacles.filter(obstacle => obstacle.y < this.canvas.height + 100);
        this.powerUps = this.powerUps.filter(powerUp => powerUp.y < this.canvas.height + 100);

        // 动态生成障碍物
        const maxObstacles = Math.min(
            GAME_CONFIG.OBSTACLES.MAX_COUNT,
            GAME_CONFIG.OBSTACLES.BASE_COUNT + this.gameState.level * 2
        );

        while (this.obstacles.length < maxObstacles) {
            this.generateObstacle();
        }

        // 动态生成道具
        const maxPowerUps = Math.min(
            GAME_CONFIG.POWER_UPS.MAX_COUNT,
            GAME_CONFIG.POWER_UPS.BASE_COUNT + Math.floor(this.gameState.level / 2)
        );

        while (this.powerUps.length < maxPowerUps) {
            this.generatePowerUp();
        }
    }

    /**
     * 生成障碍物
     */
    generateObstacle() {
        const lane = Math.random() > 0.5 ? 1 : -1;
        this.obstacles.push({
            x: this.canvas.width / 2 + lane * (Math.random() * (GAME_CONFIG.ROAD.WIDTH / 2 - 30)),
            y: -Math.random() * 200 - 30,
            width: GAME_CONFIG.OBSTACLES.WIDTH,
            height: GAME_CONFIG.OBSTACLES.HEIGHT,
            type: Math.random() > (1 - GAME_CONFIG.OBSTACLES.SPIKE_RATIO) ? 'spike' : 'rock'
        });
    }

    /**
     * 生成道具
     */
    generatePowerUp() {
        this.powerUps.push({
            x: this.canvas.width / 2 + (Math.random() - 0.5) * (GAME_CONFIG.ROAD.WIDTH - 40),
            y: -Math.random() * 400 - 30,
            width: GAME_CONFIG.POWER_UPS.WIDTH,
            height: GAME_CONFIG.POWER_UPS.HEIGHT,
            type: Math.random() > 0.5 ? 'speed' : 'shield'
        });
    }

    /**
     * 更新粒子系统
     */
    updateParticles() {
        this.particleSystem.update();
    }

    /**
     * 碰撞检测
     */
    checkCollisions() {
        // 检查与障碍物的碰撞
        this.obstacles.forEach(obstacle => {
            if (this.player.checkCollision(obstacle)) {
                this.gameOver();
            }
        });

        // 检查与道具的碰撞
        for (let i = this.powerUps.length - 1; i >= 0; i--) {
            const powerUp = this.powerUps[i];
            if (this.player.checkCollision(powerUp)) {
                this.collectPowerUp(powerUp, i);
            }
        }
    }

    /**
     * 收集道具
     * @param {Object} powerUp - 道具对象
     * @param {number} index - 道具索引
     */
    collectPowerUp(powerUp, index) {
        if (powerUp.type === 'speed') {
            this.gameState.speed = Math.min(
                this.gameState.speed + GAME_CONFIG.POWER_UPS.SPEED_BOOST,
                this.player.maxSpeed
            );
            this.particleSystem.createExplosion(
                powerUp.x,
                powerUp.y,
                GAME_CONFIG.COLORS.PARTICLE_SPEED,
                15
            );
        } else {
            this.particleSystem.createExplosion(
                powerUp.x,
                powerUp.y,
                GAME_CONFIG.COLORS.PARTICLE_SHIELD,
                15
            );
        }

        this.powerUps.splice(index, 1);
        this.gameState.addScore(GAME_CONFIG.GAME.POWER_UP_SCORE);
    }

    /**
     * 更新游戏状态
     */
    updateGameState() {
        this.gameState.updateDistance(this.gameState.speed);
        this.gameState.updateMaxSpeed(this.gameState.speed);
        this.updateUI();
    }

    /**
     * 游戏结束
     */
    gameOver() {
        this.gameState.gameOver();
        this.showGameOver();
    }

    /**
     * 显示游戏结束界面
     */
    showGameOver() {
        const state = this.gameState.getState();
        document.getElementById('finalScore').textContent = state.score;
        document.getElementById('finalDistance').textContent = state.distance;
        document.getElementById('maxSpeed').textContent = state.maxSpeed;
        document.getElementById('gameOver').style.display = 'block';
    }

    /**
     * 重新开始游戏
     */
    restart() {
        this.gameState.reset();
        this.player.reset();
        this.particleSystem.clear();
        this.obstacles = [];
        this.powerUps = [];
        document.getElementById('gameOver').style.display = 'none';
        this.updateUI();
    }

    /**
     * 更新UI
     */
    updateUI() {
        const state = this.gameState.getState();
        document.getElementById('score').textContent = state.score;
        document.getElementById('distance').textContent = state.distance;
        document.getElementById('level').textContent = state.level;
        document.getElementById('speedMeter').textContent = `速度: ${state.speed} km/h`;
    }

    /**
     * 绘制游戏
     */
    draw() {
        this.drawRoad();
        this.drawObstacles();
        this.drawPowerUps();
        this.player.draw(this.ctx);
        this.particleSystem.draw(this.ctx);
    }

    /**
     * 绘制赛道
     */
    drawRoad() {
        this.ctx.fillStyle = GAME_CONFIG.COLORS.BACKGROUND;
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

        const roadX = this.canvas.width / 2 - GAME_CONFIG.ROAD.WIDTH / 2;
        this.ctx.fillStyle = GAME_CONFIG.COLORS.ROAD;
        this.ctx.fillRect(roadX, 0, GAME_CONFIG.ROAD.WIDTH, this.canvas.height);

        // 绘制道路标线
        this.ctx.strokeStyle = '#fff';
        this.ctx.lineWidth = 3;
        this.ctx.setLineDash([20, 20]);
        this.ctx.beginPath();
        this.ctx.moveTo(this.canvas.width / 2, 0);
        this.ctx.lineTo(this.canvas.width / 2, this.canvas.height);
        this.ctx.stroke();
        this.ctx.setLineDash([]);
    }

    /**
     * 绘制障碍物
     */
    drawObstacles() {
        this.obstacles.forEach(obstacle => {
            if (obstacle.y + obstacle.height > 0 && obstacle.y < this.canvas.height) {
                this.ctx.fillStyle = obstacle.type === 'spike' ?
                    GAME_CONFIG.COLORS.SPIKE : GAME_CONFIG.COLORS.ROCK;
                this.ctx.fillRect(
                    obstacle.x - obstacle.width / 2,
                    obstacle.y,
                    obstacle.width,
                    obstacle.height
                );

                if (obstacle.type === 'spike') {
                    this.ctx.beginPath();
                    this.ctx.moveTo(obstacle.x, obstacle.y);
                    this.ctx.lineTo(obstacle.x - 10, obstacle.y + obstacle.height);
                    this.ctx.lineTo(obstacle.x + 10, obstacle.y + obstacle.height);
                    this.ctx.closePath();
                    this.ctx.fill();
                }
            }
        });
    }

    /**
     * 绘制道具
     */
    drawPowerUps() {
        this.powerUps.forEach(powerUp => {
            if (powerUp.y + powerUp.height > 0 && powerUp.y < this.canvas.height) {
                this.ctx.fillStyle = powerUp.type === 'speed' ?
                    GAME_CONFIG.COLORS.SPEED_POWER_UP : GAME_CONFIG.COLORS.SHIELD_POWER_UP;
                this.ctx.fillRect(
                    powerUp.x - powerUp.width / 2,
                    powerUp.y,
                    powerUp.width,
                    powerUp.height
                );

                // 添加发光效果
                this.ctx.shadowColor = powerUp.type === 'speed' ?
                    GAME_CONFIG.COLORS.SPEED_POWER_UP : GAME_CONFIG.COLORS.SHIELD_POWER_UP;
                this.ctx.shadowBlur = 10;
                this.ctx.fillRect(
                    powerUp.x - powerUp.width / 2,
                    powerUp.y,
                    powerUp.width,
                    powerUp.height
                );
                this.ctx.shadowBlur = 0;
            }
        });
    }

    /**
     * 游戏主循环
     */
    gameLoop() {
        this.update();
        this.draw();
        requestAnimationFrame(() => this.gameLoop());
    }
} 